<?php
/*
 * @Date: 2022-10-23 15:20:42
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2025-05-07 09:30:06
 */

namespace Ldy\Lib;

use Ldy\Models\SysConfig;

class SetClientConfig{

    // private $fileContent = '';

    private $clientConfigfileName = 'config.js';

    private $filePath = '';

    private $defConfig = [
        "APP_NAME" => '',
        // "API_URL" => '',
        "EXTEND_MODULES"=>[]
    ];


    public function generateConfig(){

        $this->get();

        $str = 'const APP_CONFIG ='. json_encode($this->defConfig);
        file_put_contents($this->filePath, $str);
        return $this;
    }

    public function get(){
         $this->filePath = public_path().DIRECTORY_SEPARATOR.$this->clientConfigfileName;

        $dbConfig = SysConfig::select();

        $dbConf = [];
        foreach($dbConfig as $item){
            $type = $item->type;
            $dbConf[$type] = $item->fields;
        }

        $sysConfig = $dbConf['sys'] ??[]; //SysConfig::where('type', 'sys')->find();

        $appName = config('admin.title','琪笙');

        if(!empty($sysConfig) && isset($sysConfig->name)) $appName = $sysConfig->name;

        $this->defConfig['APP_NAME'] = $appName;

        $this->defConfig['EXTEND_MODULES'] = config('admin.modules', []);

        $this->defConfig['APP_URL'] = config('app.app_host');

        $apiUrl = config('admin.api_url', '');
        if(!empty($sysConfig) && isset($sysConfig->api_url) && !empty($sysConfig->api_url)) $apiUrl = $sysConfig->api_url;
        if($apiUrl) $this->defConfig['API_URL'] = $apiUrl;

        $extendSetting = config('admin.extend.setting');
        if($extendSetting && method_exists($extendSetting, 'toClientConfig')) $this->defConfig = $extendSetting::toClientConfig($this->defConfig, $dbConf) ?? $this->defConfig;

        return $this->defConfig;
    }
}